package com.example.star.controller;

import com.example.star.entity.Favorite;
import com.example.star.entity.Perimeter;
import com.example.star.entity.ShoppingCart;
import com.example.star.entity.User;
import com.example.star.service.FavoriteService;
import com.example.star.service.PerimeterService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    @GetMapping("/favorites")
    @ResponseBody
    public List<Favorite> getFavorites() {
        return favoriteService.getAllFavorites();
    }

    @PostMapping("/favorites")
    @ResponseBody
    public Favorite saveFavorite(@RequestBody Favorite favorite) {
        favoriteService.saveFavorite(favorite);
        return favorite; // 返回保存的Favorite对象
    }

    @GetMapping("/favorites/items-by-user")
    @ResponseBody
    public List<Favorite> getFavoriteByuserName(@RequestParam String userName){
        return favoriteService.getFavoriteByuserName(userName);
    }
    @GetMapping("/favorite-list")
    public String showFavoriteList(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "8") int size,
                                   Model model,
                                   HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            // 用户未登录，重定向到登录页面

        }
        User user = (User) userObj;
        List<Favorite> favorites;
        int totalStars;
        if ("ADMIN".equals(user.getRole())) {
            // 管理员角色，获取所有收藏信息
            favorites = favoriteService.getFavoritesByPage(page, size);
            totalStars = favoriteService.getTotalFavorites();
        } else {
            // 普通用户角色，获取该用户的收藏信息
            favorites = favoriteService.getBuyNowsByUserName(user.getUsername(), page, size);
            totalStars = favoriteService.getTotalBuyNowsByUserName(user.getUsername());
        }
        int totalPages = (int) Math.ceil((double) totalStars / size);

        model.addAttribute("favorites", favorites);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "favorite-list";
    }

    @PostMapping("/favorites/{id}")
    public String deleteFavorites(@PathVariable int id, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        // 从 HttpSession 中获取用户信息
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            redirectAttributes.addFlashAttribute("error", "你还未登录，请先登录");
            return "redirect:/login"; // 重定向到登录页面
        }

        User user = (User) userObj;
        // 假设管理员角色名称为 "ADMIN"，根据实际情况修改
        if ("ADMIN".equals(user.getRole())) {
            try {
                favoriteService.deleteFavoriteById(id);
                redirectAttributes.addFlashAttribute("message", "收藏信息删除成功");
            } catch (Exception e) {
                redirectAttributes.addFlashAttribute("error", "删除收藏信息时出现错误：" + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "你没有权限删除收藏信息");
        }
        return "redirect:/favorite-list";
    }

    @DeleteMapping("/favorites/{id}")
    public void deleteFavoriteById(@PathVariable int id) {
        favoriteService.deleteFavoriteById(id);
    }

    @GetMapping("/favorites/{id}")
    public Favorite getFavoriteById(@PathVariable int id) {
        return favoriteService.getFavoriteById(id);
    }

    @GetMapping("/favorites/{title}")
    public Favorite getFavoriteByTitle(@PathVariable String title) {
        return favoriteService.getFavoriteByTitle(title);
    }

    @GetMapping("/favorites/check")
    @ResponseBody
    public boolean checkFavorite(@RequestParam String userName, @RequestParam String title) {
        return favoriteService.isFavorite(userName, title);
    }

    @DeleteMapping("/favorites/delete")
    @ResponseBody
    public boolean deleteFavorite(@RequestParam String userName, @RequestParam String title) {
        return favoriteService.deleteFavorite(userName, title);
    }
}